//
//  AppDelegate.m
//  Novel
//
//  Created by th on 2017/1/31.
//  Copyright © 2017年 th. All rights reserved.
//

#import "AppDelegate.h"
#import "BaseNavigationViewController.h"
#import "MainViewController.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "YFTabBarViewController.h"
#import "YFNetWorkUtil.h"
#import "UMMobClick/MobClick.h"
#import "GDTTrack.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [self setUMTJ];
    // 设置状态栏样式
    application.statusBarStyle = UIStatusBarStyleLightContent;
    application.statusBarHidden = NO;
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    
    
    YFTabBarViewController *tabbarVC = [[YFTabBarViewController alloc]init];
    //设置窗口的根控制器
    self.window.rootViewController = tabbarVC;
    
    [self.window makeKeyAndVisible];
    
    //打开网络监控
//    [Tools openNetworkMonitoring];
    [httpUtil openLog];
    [httpUtil networkStatusWithBlock:nil];
    
    //开屏广告初始化并展示代码
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        GDTSplashAd *splashAd = [[GDTSplashAd alloc] initWithAppkey:@"1106505410" placementId:@"1030125771979049"];
        splashAd.delegate = self;//设置代理1ez        
        //针对不同设备尺寸设置不同的默认图片，拉取广告等待时间会展示该默认图片。
        if ([[UIScreen mainScreen] bounds].size.height >= 568.0f) {
            splashAd.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"launch_default_567"]];
        } else {
            splashAd.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"launch_default"]];
        }
        //设置开屏拉取时长限制，若超时则不再展示广告
        splashAd.fetchDelay = 3;
        //［可选］拉取并展示全屏开屏广告
        //[splashAd loadAdAndShowInWindow:self.window];
        //设置开屏底部自定义LogoView，展示半屏开屏广告
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 100)];
        UIImageView *logo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bottom.png"]];
        [_bottomView addSubview:logo];
        logo.center = _bottomView.center;
        _bottomView.backgroundColor = [UIColor whiteColor];
        
        [splashAd loadAdAndShowInWindow:self.window withBottomView:_bottomView];
        self.splash = splashAd;
    }
    
    [self performSelector:@selector(updateShow) withObject:nil afterDelay:7.0];
    return YES;
}

//友盟统计
- (void)setUMTJ{
    
    UMConfigInstance.appKey = @"59c9e67604e2056197000d8f";
    UMConfigInstance.channelId = @"App Store";
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    ReadingManager *manager = [ReadingManager shareReadingManager];
    
    if (manager.isSave) {
        [SQLiteTool updateWithTableName: manager.bookId dict:@{@"chapter": @(manager.chapter), @"page": @(manager.page), @"status": @"0"}];
    }
    NSLog(@"----退出程序");
}

//商店id
//#define APP_STORE_ID    @"1289676475"
////项目在appstore地址
//#define APP_STORE_URL  @"itms-apps://itunes.apple.com/cn/app/id%@?mt=8"
- (void)updateShow{
    
    NSString *locationVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [[YFNetWorkUtil shareNetWorkUtil] obtainVersion:^(id data) {
        
        NSString *netVersion = data[@"ios"][@"new"];
        if (netVersion != nil && ![netVersion isKindOfClass:[NSNull class]] && netVersion.length > 0) {
            
            if (![netVersion isEqualToString:locationVersion]) {
                
                NSArray * newVerAry = [netVersion componentsSeparatedByString:@"."];
                NSArray * curVerAry = [locationVersion componentsSeparatedByString:@"."];
                for (int i = 0; i < [newVerAry count] || i < [curVerAry count]; i++)
                {
                    int newSubVer, curSubVer;
                    // 如果子版本号数不足，作为0处理
                    if (i >= [newVerAry count])
                    {
                        newSubVer = 0;
                    }
                    else
                    {
                        newSubVer = [[newVerAry objectAtIndex:i] intValue];
                    }
                    
                    if( i >= [curVerAry count])
                    {
                        curSubVer = 0;
                    }
                    else
                    {
                        curSubVer = [[curVerAry objectAtIndex:i] intValue];
                    }
                    
                    if( newSubVer > curSubVer)
                    {
                        //需要更新
                        dispatch_async(dispatch_get_main_queue(), ^{
                            
                            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"发现新版本，请前往更新" preferredStyle:UIAlertControllerStyleAlert];
                            
                            [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                
                                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",data[@"ios"][@"file"]]]];
                            }]];
                            [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
                            
                            [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertVC animated:YES completion:nil];
                        });
                        return;
                    }
                    
                }
            }
        }
    } failure:^(id error) {
        
        
    }];
    
}


-(void)splashAdSuccessPresentScreen:(GDTSplashAd *)splashAd
{
    NSLog(@"%s",__FUNCTION__);
}

-(void)splashAdFailToPresent:(GDTSplashAd *)splashAd withError:(NSError *)error
{
    NSLog(@"%s%@",__FUNCTION__,error);
}
-(void)splashAdApplicationWillEnterBackground:(GDTSplashAd *)splashAd
{
    NSLog(@"%s",__FUNCTION__);
}
-(void)splashAdClicked:(GDTSplashAd *)splashAd
{
    NSLog(@"%s",__FUNCTION__);
}

- (void)splashAdWillClosed:(GDTSplashAd *)splashAd
{
    NSLog(@"%s",__FUNCTION__);
}
-(void)splashAdClosed:(GDTSplashAd *)splashAd
{
    NSLog(@"%s",__FUNCTION__);
    _splash = nil;
}
-(void)splashAdWillPresentFullScreenModal:(GDTSplashAd *)splashAd
{
    NSLog(@"%s",__FUNCTION__);
}
-(void)splashAdDidDismissFullScreenModal:(GDTSplashAd *)splashAd
{
    NSLog(@"%s",__FUNCTION__);
}
@end
